package org.example.netty.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author 邓天天
 * @date 2021/4/5 10:49
 */
public class NettyServer {
    public static void main(String[] args) {
        // 创建BossGroup和WorkGroup  创建了两个线程组
        // bossGroup 只是处理连接
        // workGroup 真正的客户端业务处理 两个都是无限循环
        // bossGroup和workGroup 含有的子线程（NioEventLoop） 默认是ＣＰＵ线程数×２
        final NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        final NioEventLoopGroup workGroup = new NioEventLoopGroup();

        // 创建服务端启动对象，配置参数
        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 设置两个线程组
        serverBootstrap.group(bossGroup, workGroup)
                // 使用NioServerSocketChannel 作为通道实现
                .channel(NioServerSocketChannel.class)
                // 设置线程队列 等待连接个数
                .option(ChannelOption.SO_BACKLOG, 128)
                // 设置连接保持活动状态
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                // 给我们的workGroup的EventLoopGroup对应的管道设置处理器
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new NettyServerHandler());
                    }
                });
        System.out.println(".....服务器 is ready 。。。。");

        final ChannelFuture channelFuture;
        try {
            // 绑定一个端口 并且同步
            // 启动服务器(并绑定端口)
            channelFuture = serverBootstrap.bind(10010).sync();
            // 对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 关闭线程组
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();


    }
}
